
import { EnumManager_blxf } from "../Manager/EnumManager";
import PageManager_blxf from "../Manager/PageManager";
import AudioModule_blxf from "../Module/AudioModule";
import { NumModule_blxf } from "../Module/NumModule";
import PublicModule_blxf from "../Module/PublicModule";
import { UtilsModule_blxf } from "../Module/UtilsModule";

const {ccclass, property} = cc._decorator;

@ccclass
export default class DropGoldItem_blxf extends cc.Component {

    @property({ type: cc.Node, tooltip: '金币盒子' })
    goldBox: cc.Node = null;

    @property({ type: cc.Node, tooltip: '点击节点' })
    clickNode: cc.Node = null;


    @property({ tooltip: '传入参数' })
    _options: any = null;

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this.initEvent_blxf();
    }

    start () {
        this.clickNode.active = false;
    }

    initEvent_blxf () {
        this.clickNode.on('touchstart', this.onTouchGold_blxf, this);
        this.clickNode['_touchListener'].setSwallowTouches(false);
    }

    initData_blxf ( options: any ) {
        this._options = options;

        this.onDropGold_blxf();
    }

    // update (dt) {}

    /** 掉落金币 */
    onDropGold_blxf () {
        let { iconNum } = this._options;
        let num: number = Math.floor( iconNum / 5 ) || 1;
        let { PREFAB_GOLD_ITEM } = EnumManager_blxf.prefabNameType;

        for ( let i = 0; i < num; i++ ) {

            let randX = 25 - Math.random() * 50;
            let randY = 25 - Math.random() * 50;

            PageManager_blxf.instance.LoadPrefab_blxf({ 
                pfName: PREFAB_GOLD_ITEM,
                parentNode: this.goldBox,
                cb: ( goldItem: cc.Node )=>{

                    let tween: cc.Tween = cc.tween(goldItem);
                    tween.delay(i*0.13).call(()=>{
                        goldItem.active = true;
                        if (i != num - 1) return;
                        this.clickNode.active = i == num - 1;
                    }).then(cc.jumpBy(0.4, randX, randY, 50, 1)).call(()=>{
                        if (i != num - 1) return;
                    }).start();

                }
            })
        }
    }

    /** 点击金币 */
    onTouchGold_blxf () {
        AudioModule_blxf.playTouchAudio_blxf();

        let { iconType, iconNum } = this._options;
        iconType = iconType || EnumManager_blxf.gameNumType.NUM_GOLD;

        let _inP: cc.Vec3 = UtilsModule_blxf.instance.getCanvasPos_blxf( this.node );
        NumModule_blxf.instance.updateNumByType( iconType, iconNum, _inP );

        PublicModule_blxf.addDropGoldNum_blxf( -iconNum );

        let { x, y } = UtilsModule_blxf.instance.getCanvasPos_blxf( this.node );
        cc.game.emit('loadAutoNumItem_blxf', {
            x, y, isGuest: true,
            isDouble: false, rewardNum: iconNum,
        });

        this.node.destroy();
    }

}
